#!/usr/bin/env python
# encoding: utf-8


"""
@file: zhiyu.py
@time: 2016/11/16 下午5:19
"""
# 三角函数值域问题


from mathsolver.functions.base import *
from sympy import trigsimp
from mathsolver.functions.sanjiao import sanjiao_utils as su
from mathsolver.functions.budengshi import common_opers as co

from mathsolver.functions.sanjiao.jieti import SanJiaoHanShu007
from mathsolver.functions.sanjiao.zuizhi import SanJiaoHanShuZuiZhi


# 函数y=|sinx|-|cosx|的值域为().
# 函数y=sinx-sin|x|的值域是()
class ZhiYu001(BaseFunction):
    def solver(self, *args):
        self.label.add('三角函数值域')
        y_symbol, trig_f = args[0].sympify()
        seg_fs = su.segment_absed_poly(trig_f)
        seg_fs_print = ''
        simp_fs = []
        vs = []
        for seg_f in seg_fs:
            tmp_f = seg_f[0]
            tmp_simp_f = trigsimp(tmp_f)
            if tmp_simp_f.is_real:
                vs.append(tmp_simp_f)
                seg_fs_print += '  {%s} \\' % new_latex(tmp_simp_f)
                continue
            if not su.trig_simped(tmp_simp_f):
                tmp_simp_f, _ = su.trig_simp(tmp_f)
            simp_fs.append(tmp_simp_f)
            seg_fs_print += '  {%s} \\' % new_latex(tmp_simp_f)
        seg_fs_print = seg_fs_print[:seg_fs_print.rfind('\\')]
        seg_fs_print = r'\left\{ {\begin{array}{*{20}{c}} ' + seg_fs_print + r' \end{array}} \right.'
        self.steps.append([r'\because %s = %s = ' % (new_latex(y_symbol), new_latex(trig_f)), seg_fs_print])
        for tf in simp_fs:
            max_v = SanJiaoHanShuZuiZhi(verbose=True).solver(BaseEq([y_symbol, tf]), '最大值').output[0].sympify()
            min_v = SanJiaoHanShuZuiZhi(verbose=True).solver(BaseEq([y_symbol, tf]), '最小值').output[0].sympify()
            vs.append(max_v)
            vs.append(min_v)
        last_max_v = max(vs)
        last_min_v = min(vs)
        self.steps.append(
            ['根据三角函数的值域求解可得 ',
             '%s <= %s <= %s' % (new_latex(last_min_v), new_latex(y_symbol), new_latex(last_max_v))])
        self.steps.append(['故答案为: [%s, %s]' % (new_latex(last_min_v), new_latex(last_max_v)), ''])
        result_intl = Interval(last_min_v, last_max_v)
        self.output.append(co.to_base_interval(result_intl))
        return self


# 三角函数值域问题
class SanJiaoHanShuZhiYu(BaseFunction):
    CLS = [SanJiaoHanShuZuiZhi, SanJiaoHanShu007, ZhiYu001]

    def solver(self, *args):
        solve_r = None
        tmp_args = [arg for arg in args]
        if isinstance(tmp_args[0], BasePoly):
            tmp_args[0] = BaseEq(['f(x)', tmp_args[0].sympify()])
        for cl in SanJiaoHanShuZhiYu.CLS:
            try:
                solve_r = cl(known=self.known).solver(*tmp_args)
                solve_r.label.add('三角函数值域')
                break
            except Exception:
                pass
        if not solve_r:
            raise 'try fail'
        return solve_r


if __name__ == '__main__':
    r = SanJiaoHanShuZhiYu().solver(BaseValue('sqrt(3)*sin(pi*x/m)')).output[0].interval
